/*
 */

import com.thejaswi.commons.NumberBase;

/**
 *
 * @author raj
 */ 
public class ChangeBase {
    public static void main(String[] args) {
        if (args.length>0) {
            String numberStr=args[0];
            // remove initial 0s to evaluate only significant digits
            numberStr=numberStr.replaceFirst("^0+", "");
            int fromBase=(args.length>1 ? Integer.parseInt(args[1]):10);
            int newBase=(args.length>2 ? Integer.parseInt(args[2]):16);
            int spacerPos=(args.length>3 ? Integer.parseInt(args[3]):0);
            String spacerStr=(args.length>4 ? args[4] : " ");
            try {
               String newNumber=NumberBase.changeBase(numberStr, fromBase, newBase);
               System.out.print("("+fromBase+") "+numberStr + " = ");
               System.out.println("("+newBase+") "+newNumber);
               System.out.println(addSpacers(newNumber,spacerPos,spacerStr));

               // convert it back for verification
               String verifyNumber=NumberBase.changeBase(newNumber, newBase, fromBase);
               System.out.print("\nVerification: ");
               System.out.print("("+newBase+") "+newNumber + " = ");
               System.out.println("("+fromBase+") "+verifyNumber);
            }
            catch (Exception e) { 
               System.out.println("Input parameters:"+numberStr+" "+fromBase+" "+newBase);
               e.printStackTrace(); }
        }
        else {
           System.out.println();
           System.out.println("Error: Insufficient parameters!");
           System.out.println("Usage: java ChangeBase <number_in_any_base>  <current_base>  <target_base>");
           System.out.println();
           System.out.println("Examples:");
           System.out.println("java ChangeBase 20110228 10 16");  // 132DB94
           System.out.println("java ChangeBase 132DB94 16 10");   // 20110228
           System.out.println("java ChangeBase 132DB94 16 36");   // BZ15G
           System.out.println("java ChangeBase 132DB94 16 02");   // 1001100101101101110010100
           System.out.println();
        }
    }

    public static String addSpacers(String inStr, int gap, String spacer) {
       String outStr="";
       if (inStr.isEmpty() || gap==0 || inStr.isEmpty()) {
          return inStr;
       }
       char[] charArray=inStr.toCharArray();
       int charCount=0;
       for (int i=charArray.length-1; i>=0; i--) {
          charCount++;
          outStr=( i > 0 && charCount%gap==0 ) ? spacer+charArray[i]+outStr : charArray[i]+outStr;
       }
       return outStr;
    }

}
